from django.db import models
from django.utils import timezone


class Permission_group(models.Model):
    """授权组模型"""
    permit = models.SmallIntegerField(
        verbose_name='授权组',
        unique=True,
        choices=(
            (1, '管理组'), (2, '规划设计中心许可组'), (3, '商务服务组'),
            (4, '数据勘测中心许可组'), (5, '资源评价中心许可组'),
            (6, '评估咨询一中心许可组'), (7, '评估咨询二中心许可组'),
            (8, '经纪代理中心许可组'), (9, '江阴事业中心许可组'),
            (10, '南京事业中心许可组'), (11, '普通用户'), (12, '离职')
        ),
        default=11
    )

    def __str__(self):
        return str(self.get_permit_display())

    class Meta:
        db_table = '授权组'
        verbose_name = '授权组'
        verbose_name_plural = '授权组'


class Department(models.Model):
    """部门表"""
    departm = models.SmallIntegerField(
        verbose_name='部门',
        unique=True,
        choices=(
            (1, '总裁办'), (2, '信息技术部'), (3, '商务服务部'),
            (4, '计划财务部'), (5, '行政人事部'), (6, '分公司管理部'),
            (7, '规划设计中心'), (8, '数据勘测中心'), (9, '资源评价中心'),
            (10, '评估咨询一中心'), (11, '评估咨询二中心'), (12, '经纪代理中心'),
            (13, '江阴事业中心'), (14, '南京事业中心'), (15, '其它')
        ),
        default=15
    )

    def __str__(self):
        return str(self.get_departm_display())

    class Meta:
        db_table = '部门表'
        verbose_name = '部门表'
        verbose_name_plural = '部门表'


class Application(models.Model):
    """应用模型"""
    name = models.CharField(max_length=50, verbose_name='应用名称')
    icon = models.CharField(max_length=100, verbose_name='图标类名')
    color = models.CharField(max_length=20, verbose_name='颜色')
    url = models.CharField(max_length=200, blank=True, verbose_name='跳转链接')
    description = models.TextField(blank=True, verbose_name='应用描述')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    sort_order = models.IntegerField(default=0, verbose_name='排序')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    
    class Meta:
        db_table = 'application'
        verbose_name = '应用'
        verbose_name_plural = '应用'
        ordering = ['sort_order', 'id']
    
    def __str__(self):
        return self.name


class User(models.Model):
    """用户模型"""
    zh_name = models.CharField(max_length=50, unique=True, verbose_name='用户名')
    zh_pwd = models.CharField(max_length=128, verbose_name='密码')
    open_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='微信OpenID')
    wx_avatar_url = models.URLField(blank=True, null=True, verbose_name='微信头像URL')
    
    # 外键关联
    Per_group = models.ForeignKey(Permission_group, on_delete=models.CASCADE, verbose_name='权限组')
    part_id = models.ForeignKey(Department, on_delete=models.CASCADE, verbose_name='部门')
    
    # 其他字段
    per_team = models.CharField(max_length=50, blank=True, verbose_name='工作组')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    
    class Meta:
        db_table = 'user'
        verbose_name = '用户'
        verbose_name_plural = '用户'
    
    def __str__(self):
        return self.zh_name


class UserApplicationPermission(models.Model):
    """用户应用权限模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    application = models.ForeignKey(Application, on_delete=models.CASCADE, verbose_name='应用')
    permission_group = models.ForeignKey(Permission_group, on_delete=models.CASCADE, verbose_name='权限组')
    department = models.ForeignKey(Department, on_delete=models.CASCADE, verbose_name='部门')
    is_granted = models.BooleanField(default=True, verbose_name='是否授权')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    
    class Meta:
        db_table = 'user_application_permission'
        verbose_name = '用户应用权限'
        verbose_name_plural = '用户应用权限'
        unique_together = ['user', 'application']
    
    def __str__(self):
        return f"{self.user.zh_name} - {self.application.name}"


class RoleApplicationPermission(models.Model):
    """角色应用权限模型（批量权限配置）"""
    permission_group = models.ForeignKey(Permission_group, on_delete=models.CASCADE, verbose_name='权限组')
    department = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True, verbose_name='部门')
    application = models.ForeignKey(Application, on_delete=models.CASCADE, verbose_name='应用')
    is_granted = models.BooleanField(default=True, verbose_name='是否授权')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    #是否禁用，默认为False
    is_disabled = models.BooleanField(default=False, verbose_name='是否禁用')
    class Meta:
        db_table = 'role_application_permission'
        verbose_name = '角色应用权限'
        verbose_name_plural = '角色应用权限'
        unique_together = ['permission_group', 'department', 'application']
    
    def __str__(self):
        dept_name = self.department.get_departm_display() if self.department else "全部门"
        return f"{self.permission_group.get_permit_display()} - {dept_name} - {self.application.name}"